﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using SweeperPrototype.GUI.Behaviors.AttachedCommand;

namespace SweeperPrototype.GUI.Behaviors
{
    public static class GridBehaviors
    {
        public static readonly DependencyProperty SelectedItemsChangedHandlerProperty
            = DependencyProperty.RegisterAttached(
                "SelectedItemsChangedHandler",
                typeof (SimpleCommand),
                typeof (GridBehaviors),
                new FrameworkPropertyMetadata(
                    new PropertyChangedCallback(OnSelectedItemsChangedHandlerChanged)));

        public static SimpleCommand GetSelectedItemsChangedHandler(DependencyObject element)
        {
            if (element == null)
                throw new ArgumentNullException("element");
            return (SimpleCommand) element.GetValue(SelectedItemsChangedHandlerProperty);
        }

        // associate command
        public static void SetSelectedItemsChangedHandler(DependencyObject element, SimpleCommand command)
        {
            if (element == null)
                throw new ArgumentNullException("element");
            element.SetValue(SelectedItemsChangedHandlerProperty, command);
        }


        /// <summary>
        /// Called when the dependency property value is changed (new handler assigned)
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        private static void OnSelectedItemsChangedHandlerChanged(DependencyObject d,
                                                                 DependencyPropertyChangedEventArgs e)
        {
            
            DataGrid dataGrid = (DataGrid) d;

            if (e.OldValue == null && e.NewValue != null)
            {
                dataGrid.SelectionChanged += GridSelectionHandler;
            }

            if (e.OldValue != null && e.NewValue == null)
            {
                dataGrid.SelectionChanged -= GridSelectionHandler;
            }
        }


        /// <summary>
        /// Responds to the grid change. Finds our attached property. Fires delegate.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void GridSelectionHandler(object sender, SelectionChangedEventArgs e)
        {
            DataGrid dataGrid = (DataGrid) sender;

            SimpleCommand itemsChangedHandler = GetSelectedItemsChangedHandler(dataGrid);

            itemsChangedHandler.Execute(dataGrid.SelectedItems);
        }
    }
}